<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@include file="head.jsp"%>
<%@taglib uri="http://chances.com.cn/jsp/epgutils" prefix="epgutils"%>
<!DOCTYPE html>
<html>
<head>
<title>SMART_TV</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="viewport"
	content="width=device-width, initial-scale=1, maximum-scale=1">
<%@include file="/sites/weixin/js/common.jsp"%>
<%@include file="/sites/weixin/common/common_js.jsp"%>
<link rel="stylesheet" type="text/css"
	href="${_contextPath}/sites/weixin/css/wx.css" />
<script src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>
<epgutils:currUrl var="cUrl" />
<epgutils:wechatConfig debug="true" apiString="scanQRCode"
	var="tokenConfig" url="${cUrl}" />
<epgutils:wechatUrl var="bindUrl" action="bind" from="null"
	path="/wechat/bind/device.wx" />
<epgutils:wechatUrl var="unbindUrl" action="unbind" from="null"
	path="/wechat/bind/unbind.wx" />
</head>
<script>
	function init() {
		//alert("${EPG_USER_SESSION.userId}")
		console
				.log("${tokenConfig.timestamp}|${tokenConfig.noncestr}|${tokenConfig.signature}")
		wx.config({
			debug : false,
			appId : '${appId}',
			timestamp : '${tokenConfig.timestamp}',
			nonceStr : '${tokenConfig.noncestr}',
			signature : '${tokenConfig.signature}',
			jsApiList : [ 'scanQRCode', 'startRecord', 'stopRecord',
					'stopRecord', 'translateVoice' ]
		});
		wx.ready(function() {
			//alert("ready");
			//callScanQRCode();
		});
		wx.error(function(res) {
			console.log("err:[" + res.errMsg + "]");
			console.log(res);
		});
	}

	function startRecord(){
		console.log("startRecord:")
		
		document.getElementById("stopRecord_ctrl").style.display= "block";

	    //appendText("开始录音");
	    wx.startRecord();

	     wx.onVoiceRecordEnd({
		     // 录音时间超过一分钟没有停止的时候会执行 complete 回调
		     complete: function (res) {
			   	 document.getElementById("stopRecord_ctrl").style.display= "none";
			     var localId = res.localId;
			     handleLocalId(localId);
		     }
	     });

	}
	function stopRecord(){
	    //appendText("停止录音");
		document.getElementById("stopRecord_ctrl").style.display= "none";
	    
	    wx.stopRecord({
	        success: function (res) {
	            var localId = res.localId;
	            handleLocalId(localId);
	        }
	    });
	}

	function handleLocalId(localId){
	    //appendText("获取localId");

	    wx.translateVoice({
	        localId: localId, // 需要识别的音频的本地Id，由录音相关接口获得
	        isShowProgressTips: 1, // 默认为1，显示进度提示
	        success: function (res) {
	            // alert(res.translateResult); // 语音识别的结果
	            let text = res.translateResult;
	            handleText(text);
	        }
	     });
	}
	
	
	function handleText(text){
	    console.log("语音文本："+text);
	    // let divText = document.getElementById("text");
	    // divText.innerHTML = divText.innerText+"语音文件："+text;
	    //appendText("语音文本："+text);
	    if(text){
		    text = text.replace("。","");
		    text = $.trim(text);
		    document.getElementById("inputText").value= text;
		    
		    getAnalysisResult(text);
	    }else{
	    	alert("请再说一次");
	    }
	}

	function getAnalysisResult(text) {
		var data = {
			"query" : text,
			"city" : "北京",
			"category" : "movie",
			"appid" : "${tokenConfig.appId}",
			"uid" : ""
		}
		$.ajax({
					url : "${_contextPath}/wechat/proxy.wx?url="+encodeURIComponent("https://api.weixin.qq.com/semantic/semproxy/search")+"&access_token=${tokenConfig.token}",
					type : "post",
					data : JSON.stringify(data),
					processData: false,
                    contentType: 'application/json',
					success : function(data) {
						console.log(data);
						data = JSON.parse(data);
						if(data.semantic){
							appendText("分词结果：" + data.semantic.details.answer);	
							document.getElementById("stopRecord_ctrl").style.display= "none";
							gotoPage('${searchUrl}&yuyin='+data.semantic.details.answer,this,1)
						}else{
							document.getElementById("stopRecord_ctrl").style.display= "none";
							alert("未提取到关键字！请再试一次！");							
						}
					}
				});
	}

	function appendText(text) {
		let divText = document.getElementById("text");
		divText.innerHTML = divText.innerText + "<br/>" + text
	}

	function callScanQRCode() {
		wx.scanQRCode({
			needResult : 1,
			scanType : [ "qrCode", "barCode" ],
			success : function(res) {
				var result = res.resultStr;
				//alert("gotoLink url: "+result);
				
				window.location.href = result;
				//qrRefresh(result);
			}
		});
	}
	function qrRefresh(url) {
		var bindUrl = "${bindUrl}?userId=${EPG_USER_SESSION.userId}&code=";
		var qrInfo = getQrInfo(url);
		if (null == qrInfo) {
			failAlert("无效的二维码", 2000, 2000);
			return;
		}

		bindUrl = bindUrl + qrInfo;
		//alert(bindUrl);
		$.ajax({
			type : "get",
			url : bindUrl,
			async : false,
			success : function(data) {
				var msg = eval("(" + data.message + ")");
				if (msg.res_code == 0 || msg.res_code == "0") {
					window.location.href = window.location.href;
				} else {
					failAlert("绑定失败", 2000, 2000);
				}

				/*var result = trim(data);
				result=result.replace(/[\r\n]/g,"");//去掉回车换行
				if(result == 'user_not_found' || result == 'qrInfo_not_found'){
					failAlert("绑定失败",2000,2000);
				}else{
					window.location.href = window.location.href;
				}*/
			},
			error : function(XMLHttpRequest, textStatus, errorThrown) {
				failAlert("绑定失败", 2000, 2000);
			}
		});
	}
	function getQrInfo(url) {
		if (url.indexOf("/code/") == -1) {
			return null;
		}
		if (url.lastIndexOf(".wx") != -1) {
			var requestPath = url.substring(0, url.lastIndexOf(".wx"));
			var idx = requestPath.lastIndexOf("/");
			return requestPath.substring(idx + 1);
		}
	}
	function trim(str) { //删除左右两端的空格
		return str.replace(/(^\s*)|(\s*$)/g, "");
	}

	function failAlert(text, loadTime, infoTime) {
		showLoading("绑定中...");
		setTimeout(function() {
			if ($("#loadingToast")) {
				$("#loadingToast").hide();
			}
		}, loadTime);
		$("#alertDiv").html(text);
		setTimeout(function() {
			$("#alertDiv").show();
		}, loadTime);
		setTimeout(function() {
			$("#alertDiv").hide();
		}, loadTime + infoTime);
	}
</script>
<body onload="init();">
	<div id="app">
		<!-- <div align="center">
			<input type="button"
				style="width: 500px; height: 300px; font-size: 50px"
				onclick="startRecord()" value="点击开始录音" title=""></input>
		</div>
		<div align="center"
			style="width: 500px; height: 150px; text-align: center;" id="text"></div>
		<div>
			<label>测试URL中的code是：</label>
			<div id="code"></div>

			<label>测试URL中的state是：</label> <input type="text" id="state" />
		</div>
 -->
		<template v-if="binds.length > 0 "> <!-- 头部 -->
		<div class="row navbar-fixed-top menu-row">
			<div class="col-xs-2 menu-col" onclick="onBackEvent();">
				<img :src="templatePath+'/images/back.png'" class="menu-col-back" />
			</div>
			<div class="col-xs-8 menu-col">
				<span>机顶盒绑定成功</span>
			</div>
		</div>
		<div class="row row-empty">
			<div class="col-xs-12" style="padding: 0px;">
				<img :src="templatePath+'/images/machine_has.png'"
					style="max-width: 100%;" />
			</div>
		</div>
		<template v-for="(item,index) in binds">
		<div class="row binds" :id="'person_'+index"
			style="margin-bottom: 14px; margin-left: 0px; margin-right: 0px;">
			<div class="col-xs-1" style="margin-right: 0px; padding-right: 0px;">
				<img alt="Brand" :src="templatePath+'/images/machine_s.png'"
					style="max-width: 20px;" />
			</div>
			<div class="col-xs-9" style="padding-top: 3px;">
				<span style="color: #00a7ba;" v-text="item.stbNo"></span>
			</div>
			<div class="col-xs-2" @click="unBind('person_'+index,item.stbNo)"
				style="text-align: -webkit-center; padding: 0px;">
				<span>解绑</span>
			</div>
		</div>
		</template> </template>

		<template v-if="length <= 0 "> <!-- 头部 -->
		<div class="navbar-fixed-top menu-row">
			<div class="col-xs-2 menu-col" onclick="onBackEvent();">
				<img :src="templatePath+'/images/back.png'" class="menu-col-back" />
			</div>
			<div class="col-xs-8 menu-col">
				<span>机顶盒未绑定</span>
			</div>
			<div class="col-xs-2" style="padding-top: 8px;">
				<a href="javascript:callScanQRCode();"> <img
					:src="templatePath+'/images/ew.png'" style="max-height: 22px" />
				</a>
			</div>
		</div>
		<div class="row row-content" style="margin-top: 3.5em;">
			<div class="col-xs-12">
				<img :src="templatePath+'/images/machine.png'"
					style="max-width: 100%;" />
			</div>
		</div>
		</template>
	</div>

	<!-- bottom tip layer -->
	<div id="bottomTip" class="navbar-fixed-bottom alert-unbind">
		<span id="bottomTipTxt"> <!-- &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"手机（手机号）与机顶盒（型号）已解除绑定,欲恢复捆绑，请重新扫描绑定二维码" -->
		</span>
	</div>

	<!-- 提示尚未登录 -->
	<!-- 提示登录蒙版 -->
	<div id="alertDiv" class="alert-div">绑定失败！</div>

	<script>
		var vm = new Vue({
			el : "#app",
			data : {
				templatePath : '${_templatePath}',
				binds : weixinOption.bind,
				length : weixinOption.bind.length
			},
			methods : {
				unBind : unBind
			}
		});
		function unBind(id, stbNo) {
			/* bindCtrl.remove(stbNo,function(){
				$("#"+id).remove();
				$("#bottomTipTxt").html('&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"用户（'+nickname+'）与机顶盒（'+stbNo+'）已解除绑定,欲恢复捆绑，请重新扫描绑定二维码"');
				$("#bottomTip").show();
				if($(".binds").length <= 0) {
					setTimeout("refreshPage()", 3000);
				}
			}); */
			$
					.ajax({
						method : "get",
						url : "${unbindUrl}?userId=${EPG_USER_SESSION.userId}&stbNo="
								+ stbNo,
						async : false,
						success : function(data) {
							//console.log(data)
							var msg = eval("(" + data.message + ")");
							if (msg.res_code == 0 || msg.res_code == "0") {
								$("#" + id).remove();
								$("#bottomTipTxt")
										.html(
												'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"用户（${EPG_USER_SESSION.wechatUser.nickname}）与机顶盒（'
														+ stbNo
														+ '）已解除绑定,欲恢复捆绑，请重新扫描绑定二维码"');
								$("#bottomTip").show();
								setTimeout("refreshPage()", 1500);
								/*if($(".binds").length <= 0) {
									setTimeout("refreshPage()", 3000);
								}*/
							}
							//console.log("unbind");
							//console.log(data);
							//binds = data.result;
							//alert(data);
						},
						error : function(XMLHttpRequest, textStatus,
								errorThrown) {
							//alert(XMLHttpRequest);
							//alert(textStatus);
							alert(errorThrown);
						},
						failure : function() {
							//console.log("failed");
						}
					});

		}

		function refreshPage() {
			window.location.href = window.location.href;
		}
	</script>
	<%@include file="/sites/weixin/common/bodyEndVm.jsp"%>
</body>
</html>
